package com.ojoin.trade.common.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ojoin.trade.common.Constants;

public class VerityCodeUtils {

	private static final Logger log = LoggerFactory
			.getLogger(VerityCodeUtils.class);

	public static String getDownloadDir() {
		return System.getProperties().getProperty("user.home") + File.separator
				+ "Downloads";
	}

	public static final String VerifyImgPath = getDownloadDir() + "/test.jpg";
	// public static final String VerifyImgPath = getDownloadDir() +
	// "/verifycode.png";

	public static final int VERIFYTYPE_FILE = 0; // 图片存为文件后读取校验码
	public static final int VERIFYTYPE_BYTE = 1; // 读取校验码图片的字节流来获取

	public static String getVerifyCode(int verifytype, String filename,
			byte[] imgbytes) {
		try {
			// 换行符
			final String newLine = "\r\n";
			final String boundaryPrefix = "--";
			// 定义数据分隔线
			String BOUNDARY = "----WebKitFormBoundaryKyy2rsC4lOW6tnIw";
			// 服务器的域名
			URL url = new URL(
					"http://bbb4.hyslt.com/api.php?mod=php&act=upload");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			// 设置为POST情
			conn.setRequestMethod("POST");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			// 设置请求头参数
			conn.setRequestProperty("Host", "bbb4.hyslt.com");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("Charsert", Constants.ENCODING);
			conn.setRequestProperty(
					"User-Agent",
					"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36");
			conn.setRequestProperty("Content-Type",
					"multipart/form-data; boundary=" + BOUNDARY);
			OutputStream out = new DataOutputStream(conn.getOutputStream());
			StringBuilder sb = new StringBuilder();
			sb.append(boundaryPrefix);
			sb.append(BOUNDARY);
			sb.append(newLine);
			sb.append("Content-Disposition: form-data;name=\"user_name\""
					+ newLine);
			sb.append(newLine);
			sb.append("18join" + newLine);

			sb.append(boundaryPrefix);
			sb.append(BOUNDARY);
			sb.append(newLine);
			sb.append("Content-Disposition: form-data;name=\"user_pw\""
					+ newLine);
			sb.append(newLine);
			sb.append("13572468" + newLine);

			sb.append(boundaryPrefix);
			sb.append(BOUNDARY);
			sb.append(newLine);
			sb.append("Content-Disposition: form-data;name=\"yzm_minlen\""
					+ newLine);
			sb.append(newLine);
			sb.append("" + newLine);

			sb.append(boundaryPrefix);
			sb.append(BOUNDARY);
			sb.append(newLine);
			sb.append("Content-Disposition: form-data;name=\"yzm_maxlen\""
					+ newLine);
			sb.append(newLine);
			sb.append("" + newLine);

			sb.append(boundaryPrefix);
			sb.append(BOUNDARY);
			sb.append(newLine);
			sb.append("Content-Disposition: form-data;name=\"yzmtype_mark\""
					+ newLine);
			sb.append(newLine);
			sb.append("png" + newLine);

			sb.append(boundaryPrefix);
			sb.append(BOUNDARY);
			sb.append(newLine);
			sb.append("Content-Disposition: form-data;name=\"zztool_token\""
					+ newLine);
			sb.append(newLine);
			sb.append("" + newLine);

			sb.append(boundaryPrefix);
			sb.append(BOUNDARY);
			sb.append(newLine);
			sb.append("Content-Disposition: form-data;name=\"upload\";filename=\"1.jpg\""
					+ newLine);//
			sb.append("Content-Type: image/jpg" + newLine);
			sb.append(newLine);
			//log.info("Request body:\n" + sb.toString() + "\n");
			// 将参数头的数据写入到输出流中
			out.write(sb.toString().getBytes());

			if (verifytype == VERIFYTYPE_FILE) {
				File file = new File(filename);
				// 数据输入流,用于读取文件数据
				DataInputStream in = new DataInputStream(new FileInputStream(
						file));
				byte[] bufferOut = new byte[1024];
				int bytes = 0;
				while ((bytes = in.read(bufferOut)) != -1) {
					out.write(bufferOut, 0, bytes);
				}
				in.close();
			} else if (verifytype == VERIFYTYPE_BYTE) {
				if(null !=imgbytes && imgbytes.length>0 ){
					out.write(imgbytes);
				}else {
					return null;
				}
				
			}
			out.write(newLine.getBytes());
			// 定义最后数据分隔线，即--加上BOUNDARY再加上--。
			byte[] end_data = (newLine + boundaryPrefix + BOUNDARY
					+ boundaryPrefix + newLine).getBytes();
			// 写上结尾标识
			out.write(end_data);
			out.flush();
			out.close();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				String[] split = line.split("\"");
				if (split != null && split.length == 11)
					return split[9];
				// String seperator = "\"val\":\"";
				// int start = line.indexOf(seperator);
				// if (start > 0) {
				// return line.substring(start + seperator.length(), start
				// + seperator.length() + 5);
				// }
			}
			return null;
		} catch (Exception e) {
			log.error("发送POST请求出现异常！", e);
		}
		return null;
	}

	public static void byte2File(byte[] buf) {
		BufferedOutputStream bos = null;
		FileOutputStream fos = null;
		File file = null;
		try {
			File dir = new File(getDownloadDir());
			if (!dir.exists() && dir.isDirectory()) {
				dir.mkdirs();
			}
			file = new File(VerifyImgPath);
			fos = new FileOutputStream(file);
			bos = new BufferedOutputStream(fos);
			bos.write(buf);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 获得指定文件的byte数组
	 */
	public static byte[] getBytes(String filePath) {
		byte[] buffer = null;
		try {
			File file = new File(filePath);
			FileInputStream fis = new FileInputStream(file);
			ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
			byte[] b = new byte[1000];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			fis.close();
			bos.close();
			buffer = bos.toByteArray();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buffer;
	}

	public static void main(String[] args) {
		// String verifyCodeUrl = "http://www.18join.com/img/test.jpg";
		// byte[] imgbytes1 = getImageByteArrays(verifyCodeUrl);
		// byte[] imgbytes2 = getBytes(VerifyImgPath);
		// String verifyCode1 =
		// VerityCodeUtils.getVerifyCode(VerityCodeUtils.VERIFYTYPE_BYTE, null,
		// imgbytes1);
		// String verifyCode2 =
		// VerityCodeUtils.getVerifyCode(VerityCodeUtils.VERIFYTYPE_BYTE, null,
		// imgbytes2);
		//
		// System.out.println("verifyCode1->" + verifyCode1);
		// System.out.println("verifyCode2->" + verifyCode2);

		String verifyCode = VerityCodeUtils.getVerifyCode(
				VerityCodeUtils.VERIFYTYPE_FILE, VerifyImgPath, null);
		System.out.println("verifyCode->" + verifyCode);
	}
 
	public static byte[] getImageByteArrays(String verifyCodeUrl) {
		URL url;
		BufferedInputStream bis = null;
		HttpURLConnection httpUrl = null;
		try {
			url = new URL(verifyCodeUrl);

			int BUFFER_SIZE = 1024*1024;
			//byte[] total = new byte[1024*1024];
			byte[] buf = new byte[BUFFER_SIZE];
			int tsize = 0;
			int size = 0;
			
			httpUrl = (HttpURLConnection) url.openConnection();
		
			httpUrl.connect();
			bis = new BufferedInputStream(httpUrl.getInputStream());

			while ((size = bis.read(buf)) != -1) {
				tsize += size ;
				// System.arraycopy(data1,0,data3,0,data1.length);
			}

			bis.close();
			byte[] total = new byte[tsize];
			System.arraycopy(buf,0,total,0, tsize);
			
			return total;
		} catch (MalformedURLException e) {
			LogUtils.error(log, e, e.getMessage());
		} catch (IOException e) {
			LogUtils.error(log, e, e.getMessage());
		}
		return null;
	}
   
	
	
	
	
	
	
	public static void saveIMG(String verifyCodeUrl, String filename) {
		URL url;
		FileOutputStream fos = null;
		BufferedInputStream bis = null;
		HttpURLConnection httpUrl = null;
		try {
			url = new URL(verifyCodeUrl);
 
			int BUFFER_SIZE = 1024;
			byte[] buf = new byte[BUFFER_SIZE];
			int size = 0;
 
			httpUrl = (HttpURLConnection) url.openConnection();
			httpUrl.connect();
			bis = new BufferedInputStream(httpUrl.getInputStream());
			fos = new FileOutputStream(filename);
			while ((size = bis.read(buf)) != -1) {
				fos.write(buf, 0, size);
			}
			
			fos.close();
		} catch (MalformedURLException e) {
			LogUtils.error(log, e, e.getMessage());
		} catch (IOException e) {
			LogUtils.error(log, e, e.getMessage());
		}
	}

	 
	public static void saveIMG(byte[]  bytes,String filename) {
		FileOutputStream fos = null;
		try {
			
			fos = new FileOutputStream(filename);
			
			fos.write(bytes, 0, bytes.length);

			fos.close();
		} catch (MalformedURLException e) {
			LogUtils.error(log, e, e.getMessage());
		} catch (IOException e) {
			LogUtils.error(log, e, e.getMessage());
		}
	}
	
	
}
